package com.houkunlin.configuration;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * Jackson 解析 Json 字符串参数去除首尾空格
 *
 * @author HouKunLin
 */
@Configuration
public class StringTrimJacksonConfiguration {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
                .deserializerByType(String.class, new StdScalarDeserializer<String>(String.class) {
                    @Override
                    public String deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
                        final String value = p.getValueAsString();
                        if (value == null) {
                            return null;
                        }
                        return StringUtils.trimToEmpty(value);
                    }
                });
    }
}
